package com.yixun.qfbao.hander;

import com.alibaba.fastjson.JSONObject;
import com.yixun.qfbao.api.service.PremisesRecommenderService;
import com.yixun.qfbao.apidto.AddPremisesRecommenderReqDto;
import com.yixun.qfbao.dto.base.BaseRequestDTO;
import com.yixun.qfbao.dto.base.BaseResponseDTO;
import com.yixun.qfbao.hander.base.CommonAbstractHander;
import com.yixun.qfbao.vo.AddPremisesRecommenderReqVo;
import com.yixun.qfbao.xf.model.PremisesRecommender;
import com.yixun.qfbao.xf.model.dto.PremisesDto;
import com.yixun.qfbao.xf.model.enums.PremisesStatusEnum;
import com.yixun.qfbao.xf.model.enums.ResultEnum;
import com.yixun.qfbao.xf.service.PremisesService;
import org.apache.commons.collections.CollectionUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * @program: channel-parent
 *
 * @description: 新增楼盘推荐人
 *
 * @author: Seven.wang
 *
 * @create: 2019-11-05 13:59
 **/
@Service("addPremisesRecommenderHander")
public class AddPremisesRecommenderHander extends CommonAbstractHander {

    private static Logger log = Logger.getLogger(AddPremisesRecommenderHander.class);

    @Autowired
    PremisesRecommenderService premisesRecommenderService;
    @Autowired
    PremisesService premisesService;

    @Override
    public BaseResponseDTO doBusiness(BaseRequestDTO reqDto) {
        AddPremisesRecommenderReqVo req = (AddPremisesRecommenderReqVo)reqDto;
        AddPremisesRecommenderReqDto reqDto1 = req.getParams();
        BaseResponseDTO resDto = new BaseResponseDTO();
        try {
            if(reqDto1.getPremisesId() == null){
                resDto.setResult(ResultEnum.FAIL.getNo());
                resDto.setErrorMsg("楼盘信息不存在!");
                return resDto;
            }
            // 查询当前楼盘的推荐人列表
            List<PremisesRecommender> oldList = premisesRecommenderService.selectPremisesRecommenderByPremisesId(reqDto1.getPremisesId());
            List<PremisesRecommender> addList = new ArrayList<>();
            if(reqDto1.getRecommenderId() != null && reqDto1.getRecommenderId().size() > 0){
                addList = buildAddPremisesRecommenderList(reqDto1, oldList);
            }
            // 构建页面传递的推荐人列表
            List<PremisesRecommender> requestList = buildRequestPremisesRecommenderList(reqDto1);
            // 构建需删除的推荐人列表
            List<PremisesRecommender> removeList = buildRemovePremisesRecommenderList(requestList,oldList);
            if(CollectionUtils.isNotEmpty(oldList) && CollectionUtils.isNotEmpty(removeList)){
                premisesRecommenderService.batchDeleted(removeList);
            }
            if(CollectionUtils.isNotEmpty(addList)){
                premisesRecommenderService.batchAdd(addList);
            }
            log.info("AddPremisesRecommenderHander is [success]: 【Parame】："+ JSONObject.toJSONString(reqDto1));

            // 推荐人变更,楼盘待审核
            PremisesDto premisesDto = new PremisesDto();
            premisesDto.setId(reqDto1.getPremisesId());
            premisesDto.setPremisesStatus(PremisesStatusEnum.type0.getNo());
            premisesService.update(premisesDto);

            resDto.setResult(ResultEnum.SUCCESS.getNo());
            resDto.setErrorMsg("添加成功!");
        }catch (Exception e) {
            log.info("AddPremisesRecommenderHander is error: {}", e);
            resDto.setResult(ResultEnum.FAIL.getNo());
            resDto.setErrorMsg("添加推荐人失败!");
        }
        return resDto;
    }

    /**
     *  构建新增的推荐人列表
     * @param dto
     * @param oldList
     * @return
     */
    private List<PremisesRecommender> buildAddPremisesRecommenderList(AddPremisesRecommenderReqDto dto, List<PremisesRecommender> oldList){
        List<PremisesRecommender> list = new ArrayList<>();
        for(Long rid : dto.getRecommenderId()){
            // 是否是新增的推荐人
            boolean isPass = true;
            // 如果没有添加过推荐人，则全部为新增的推荐人
            if(CollectionUtils.isNotEmpty(oldList)){
                for(PremisesRecommender op : oldList){
                    // 如果已在推荐人列表存在,则不重复添加
                    if(rid.equals(op.getRecommenderId())){
                        isPass = false;
                        break;
                    }
                }
            }
            if(!isPass){
                continue;
            }
            PremisesRecommender pr = new PremisesRecommender();
            pr.setPremisesId(dto.getPremisesId());
            pr.setRecommenderId(rid);
            pr.setRecommenderUuid(UUID.randomUUID().toString().replace("-", ""));
            pr.setCreateUserId(Long.parseLong(dto.getUserId() == null ? "0" : dto.getUserId()));
            pr.setUpdateUserId(Long.parseLong(dto.getUserId() == null ? "0" : dto.getUserId()));
            pr.setCreateTime(new Date());
            pr.setUpdateTime(new Date());
            pr.setDelFlag("0");
            list.add(pr);
        }
        return list;
    }

    /**
     *  构建页面传值列表
     * @param dto
     * @param oldList
     * @return
     */
    private List<PremisesRecommender> buildRequestPremisesRecommenderList(AddPremisesRecommenderReqDto dto){
        List<PremisesRecommender> list = new ArrayList<>();
        for(Long rid : dto.getRecommenderId()){
            PremisesRecommender pr = new PremisesRecommender();
            pr.setPremisesId(dto.getPremisesId());
            pr.setRecommenderId(rid);
            pr.setRecommenderUuid(UUID.randomUUID().toString().replace("-", ""));
            pr.setCreateUserId(Long.parseLong(dto.getUserId() == null ? "0" : dto.getUserId()));
            pr.setUpdateUserId(Long.parseLong(dto.getUserId() == null ? "0" : dto.getUserId()));
            pr.setCreateTime(new Date());
            pr.setUpdateTime(new Date());
            pr.setDelFlag("0");
            list.add(pr);
        }
        return list;
    }

    /**
     *  构建需删除的推荐人列表
     * @param addList
     * @param oldList
     * @return
     */
    private List<PremisesRecommender> buildRemovePremisesRecommenderList(List<PremisesRecommender> requestList, List<PremisesRecommender> oldList){
        List<PremisesRecommender> removePremisesRecommenderList = new ArrayList<>();
        for(PremisesRecommender op : oldList){
            boolean needRemove = true;
            // 如果新增推荐人为空，则取消所有推荐人
            if(CollectionUtils.isNotEmpty(requestList)){
                for (PremisesRecommender np : requestList){
                    if(np.getRecommenderId().equals(op.getRecommenderId())){
                        needRemove = false;
                        break;
                    }
                }
            }
            if(needRemove){
               removePremisesRecommenderList.add(op);
            }
        }
        return removePremisesRecommenderList;
    }
}
